package com.lgb.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //返回数据对象
    private class RequestLog{
        //请求的url
        private String url;
        //访问的ip
        private String ip;
        //请求的类
        private String classMethod;
        //请求的对象数组
        private Object[] args;

        //构造方法
        public RequestLog(String url , String ip , String classMethod , Object[] args){
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args =args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

    @Pointcut("execution(* com.lgb.controller.*.*(..))")
    public void log(){

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取访问的url
        String url = request.getRequestURI();
        //获取访问的ip
        String ip = request.getRemoteAddr();
        //获取访问的类
        String ClassMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        //请求的参数
        Object[] args = joinPoint.getArgs();
        //构造对象
        RequestLog requestLog = new RequestLog(url,ip,ClassMethod,args);
        //输出
        logger.info("Request:{}",requestLog);
    }

    @After("log()")
    public void doAfter(){
        logger.info("------------after-----------");
    }

    @AfterReturning(returning = "result" , pointcut = "log()")
    public void doAfterReturn(Object result){
        logger.info("Result : {}" , result);
    }
}
